package com.tt.job.rocketmq;

import com.alibaba.rocketmq.client.consumer.DefaultMQPushConsumer;
import com.alibaba.rocketmq.client.exception.MQClientException;
import com.alibaba.rocketmq.common.protocol.heartbeat.MessageModel;
import com.tt.job.api.Job;
import com.tt.job.api.JobMode;
import com.tt.job.executor.JobMessageConcurrentlyExecutor;
import com.tt.job.executor.JobMessageOrderlyExecutor;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledThreadPoolExecutor;

@Component
public class MqConsumer {
    private final static Logger logger = LoggerFactory.getLogger(MqConsumer.class);
    private final ScheduledThreadPoolExecutor executorService;
    private Map<String, DefaultMQPushConsumer> consumerMap = new ConcurrentHashMap<>();
    /**
     * 用于进行任务处理的线程池的大小
     */
    @Value("${job.worker.threads:16}")
    private int poolSize;
    @Autowired
    private MqSettings settings;


    public MqConsumer() {
        executorService = new ScheduledThreadPoolExecutor(poolSize);
    }

    /**
     * 订阅指定job的消息
     *
     * @param jobClass
     * @param job
     * @return
     */
    public synchronized boolean subscribe(String jobClass, Job job) throws MQClientException {
        if (consumerMap.containsKey(jobClass)) {
            return true;
        }
        String mqFlag = jobClass.replace(".", "-");
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer();
        //设置消息消费模式，默认集群模式
        //consumer.setMessageModel(MessageModel.BROADCASTING);
        consumer.setNamesrvAddr(settings.getNameServer());
        consumer.setConsumerGroup(settings.getGroup() + "|" + mqFlag);
        // 设置instname为 {jobClass}@{yyyyMMddHHmmssSSS}
        // 之前instname的值位 jobClass， 导致在一台机器上起多个cluster-job时，clientId重复。
        // clientid重复导致即使是同一个consumerGroup，多个进程也会消费同一条消息
        consumer.setInstanceName(String.format("%s@%s", jobClass, DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS")));
        consumerMap.put(jobClass, consumer);
        consumer.subscribe(settings.getTopic(), mqFlag);
        if (job.getMode() == JobMode.ORDERLY) {
            consumer.registerMessageListener(new JobMessageOrderlyExecutor(executorService, job, settings.getMaxReconsumeTimes()));
        } else {
            consumer.registerMessageListener(new JobMessageConcurrentlyExecutor(executorService, job, settings.getMaxReconsumeTimes()));
        }
        consumer.start();
        logger.info("开始订阅Job:{}", jobClass);
        return true;
    }

    public synchronized boolean unsubscribe(String jobClass) {
        if (consumerMap.containsKey(jobClass)) {
            try {
                DefaultMQPushConsumer consumer = consumerMap.remove(jobClass);
                if (consumer != null) {
                    consumer.shutdown();
                }
            } catch (Exception e) {
                logger.error("shutdown consumer error.", e);
                return false;
            }
        }
        logger.info("取消订阅任务 Job:{}", jobClass);
        return true;
    }

    /**
     * 移除对所有事件的监听
     */
    public synchronized boolean unsubscribeAll() {
        for (DefaultMQPushConsumer consumer : consumerMap.values()) {
            try {
                consumer.shutdown();
            } catch (Exception e) {
                logger.error("shutdown consumer error. consumer:{}", consumer, e);
            }
        }
        consumerMap.clear();
        logger.info("清空所有订阅任务");
        return true;
    }

}
